package lsdm.jmeter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Hello world!
 */
public class FastJsonUtil {

    public static String readJsonFile(String dir, String readFile) {
        File file = new File(dir + readFile);
        try {
//            读取JSON文件
            FileReader fileReader = new FileReader(file);
            int ch = 0;
//            存放读取后的数据
            StringBuffer sb = new StringBuffer();
            while ((ch = fileReader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            String rs = sb.toString();
//            jmeter获取响应数据
//            json文件处理
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param jsonStr 带处理的JSON字符串
     */
    public static void jsonDataHander(String dir, String writeFile, String jsonStr) {
//        将字符串转JSON对象
        JSONObject jsonObj = JSON.parseObject(jsonStr);
//        获取data数组
        JSONArray data = jsonObj.getJSONArray("data");
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(dir + writeFile, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject user = data.getJSONObject(i);
            String userName = user.getString("loginName");
            String realName = user.getString("userName");
            try {
                fileWriter.write(userName + "," + "123," + realName + "\r\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
